/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.controller.func;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.je.common.base.DynaBean;
import com.je.common.base.constants.Enable;
import com.je.common.base.constants.FunCopyType;
import com.je.common.base.entity.func.FuncInfo;
import com.je.common.base.exception.PlatformException;
import com.je.common.base.exception.PlatformExceptionEnum;
import com.je.common.base.mapper.query.Condition;
import com.je.common.base.mapper.query.ConditionEnum;
import com.je.common.base.mapper.query.Query;
import com.je.common.base.mvc.AbstractPlatformController;
import com.je.common.base.mvc.BaseMethodArgument;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.result.DirectJsonResult;
import com.je.common.base.service.CommonService;
import com.je.common.base.service.QueryBuilderService;
import com.je.common.base.service.rpc.BeanService;
import com.je.common.base.service.rpc.SystemSettingRpcService;
import com.je.common.base.util.*;
import com.je.core.entity.extjs.JSONTreeNode;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.ibatis.extension.plugins.pagination.Page;
import com.je.meta.cache.func.FuncConfigCache;
import com.je.meta.cache.func.FuncInfoCache;
import com.je.meta.cache.func.FuncStaticizeCache;
import com.je.meta.service.common.MetaDevelopLogService;
import com.je.meta.service.func.MetaFuncInfoService;
import com.je.meta.service.setting.MetaSystemSettingService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 功能配置管理
 */
@RestController
@RequestMapping(value = "/je/meta/funcInfo")
public class FuncInfoController extends AbstractPlatformController {

    @Autowired
    private MetaDevelopLogService developLogService;
    @Autowired
    protected MetaFuncInfoService funcInfoService;
    @Autowired
    private MetaSystemSettingService systemSettingService;
    @Autowired
    private SystemSettingRpcService systemSettingRpcService;
    @Autowired
    private FuncStaticizeCache funcStaticizeCache;
    @Autowired
    private QueryBuilderService queryBuilderService;
    @Autowired
    private FuncInfoCache funcInfoCache;
    @Autowired
    private FuncConfigCache funcConfigCache;
    @Autowired
    private CommonService commonService;

    @RequestMapping(value = "/addWorkflowFild", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult addMoRen(BaseMethodArgument param, HttpServletRequest request) {

        String type = "FUNC,TREE,VIEW";
        List<DynaBean> funclist = metaService.select("JE_CORE_FUNCINFO",ConditionsWrapper.builder()
                .ne("JE_CORE_FUNCINFO_ID","ROOT").in("FUNCINFO_FUNCTYPE",Arrays.asList(type.split(","))));
        for(DynaBean func:funclist){
            String funcId = func.getStr("JE_CORE_FUNCINFO_ID");
            List<DynaBean> fileds = metaService.select("JE_CORE_RESOURCEFIELD",
                    ConditionsWrapper.builder().eq("RESOURCEFIELD_FUNCINFO_ID",funcId).orderByDesc("SY_ORDERINDEX"));
            if(fileds==null || fileds.size()==0){
                continue;
            }
            String SY_ORDERINDEX = fileds.get(0).getStr("SY_ORDERINDEX");
            int order = Integer.parseInt(SY_ORDERINDEX)+1;
            String sysMode = func.getStr("FUNCINFO_SYSMODE");
            DynaBean rf = new DynaBean("JE_CORE_RESOURCEFIELD", false);
            rf.set(BeanService.KEY_PK_CODE, "JE_CORE_RESOURCEFIELD_ID");
            rf.set("RESOURCEFIELD_USE_SCOPE", "ALL");
            rf.set("RESOURCEFIELD_XTYPE", "workflowhistory");
            //将导入的字段标识为true
            rf.set("RESOURCEFIELD_IFIMPL", "1");
            //是否可用  true
            rf.set("RESOURCEFIELD_DISABLED", "1");
            //是否可以为空  true
            rf.set("RESOURCEFIELD_ALLOWBLANK", "1");
            //默认序号为0
            rf.set("SY_ORDERINDEX", order);
            //所占行数
            rf.set("RESOURCEFIELD_ROWSPAN", 1);
            //所占列数
            rf.set("RESOURCEFIELD_COLSPAN", 1);
            //可选可编辑   默认否
            rf.set("RESOURCEFIELD_EDITABLE", "0");
            rf.set("RESOURCEFIELD_HIDDEN", "1");
            rf.set("RESOURCEFIELD_CODE", "__workflow_history");
            rf.set("RESOURCEFIELD_NAME", "审批记录");
            rf.set("RESOURCEFIELD_NAME_EN", "");
            rf.set("RESOURCEFIELD_FUNCINFO_ID", funcId);
            rf.set("RESOURCEFIELD_SYSMODE", sysMode);
            commonService.buildModelCreateInfo(rf);
            metaService.insert(rf);
        }
        return BaseRespResult.successResult("操作成功");
    }

    @RequestMapping(value = "/getJsEvent", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult getJsEvent(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = new DynaBean();
        dynaBean.put("type", getStringParameter(request, "type"));
        dynaBean.put("funcId", getStringParameter(request, "funcId"));
        dynaBean.put("id", getStringParameter(request, "id"));
        List<Map<String, Object>> list = funcInfoService.getJsEvent(dynaBean);
        return BaseRespResult.successResult(list);
    }

    /**
     * 加载表格树
     *
     * @param param
     */
    @RequestMapping(value = "/loadGridTree", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult loadGridTree(BaseMethodArgument param, HttpServletRequest request) {
        Query query = param.buildQuery();
        Condition condition = query.findCondition("SY_JESYS", "1");
        if ("1".equals(systemSettingRpcService.findSettingValue("SY_JECORE"))) {
            if (condition != null) {
                condition.setCode("");
                condition.setType("or".equalsIgnoreCase(condition.getCn()) ? ConditionEnum.OR.getType() : ConditionEnum.AND.getType());
                Condition sysJesys = new Condition("SY_JESYS", ConditionEnum.EQ.getType(), "1");
                Condition sysJecore = new Condition("SY_JECORE", ConditionEnum.NE.getType(), "1", ConditionEnum.OR.getType());
                condition.setValue(Lists.newArrayList(sysJesys, sysJecore));
            } else {
                query.addCustom("SY_JECORE", ConditionEnum.NE, "1");
            }
        } else if (condition != null) {
            query.getCustom().remove(condition);
        }
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> records = manager.loadGridTree(param, request);
        if (records != null) {
            result.put("children", records);
            result.put("totalCount", records.size());
        }
        return BaseRespResult.successResult(DirectJsonResult.buildObjectResult(result));
    }

    /**
     * 加载表格树
     *
     * @param param
     */
    @RequestMapping(value = "/loadGridTreeData", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult loadGridTreeData(BaseMethodArgument param, HttpServletRequest request) {
        Query query = param.buildQuery();
        Condition condition = query.findCondition("SY_JESYS", "1");
        if ("1".equals(systemSettingRpcService.findSettingValue("SY_JECORE"))) {
            if (condition != null) {
                condition.setCode("");
                condition.setType("or".equalsIgnoreCase(condition.getCn()) ? ConditionEnum.OR.getType() : ConditionEnum.AND.getType());
                Condition sysJesys = new Condition("SY_JESYS", ConditionEnum.EQ.getType(), "1");
                Condition sysJecore = new Condition("SY_JECORE", ConditionEnum.NE.getType(), "1", ConditionEnum.OR.getType());
                condition.setValue(Lists.newArrayList(sysJesys, sysJecore));
            } else {
                query.addCustom("SY_JECORE", ConditionEnum.NE, "1");
            }
        } else if (condition != null) {
            query.getCustom().remove(condition);
        }
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> records = manager.loadGridTree(param, request);
        if (records != null) {
            result.put("children", records);
            result.put("totalCount", records.size());
        }
        return BaseRespResult.successResult(DirectJsonResult.buildObjectResult(result));
    }

    /**
     * 加载功能配置
     *
     * @param param
     */
    @RequestMapping(value = "/load", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @Override
    public BaseRespResult load(BaseMethodArgument param, HttpServletRequest request) {
        Query query = param.buildQuery();
        Condition condition = query.findCondition("SY_JESYS", "1");
        if ("1".equals(systemSettingRpcService.findSettingValue("SY_JECORE"))) {
            if (condition != null) {
                condition.setCode("");
                condition.setType("or".equalsIgnoreCase(condition.getCn()) ? ConditionEnum.OR.getType() : ConditionEnum.AND.getType());
                Condition sysJesys = new Condition("SY_JESYS", ConditionEnum.EQ.getType(), "1");
                Condition sysJecore = new Condition("SY_JECORE", ConditionEnum.NE.getType(), "1", ConditionEnum.OR.getType());
                condition.setValue(Lists.newArrayList(sysJesys, sysJecore));
            } else {
                query.addCustom("SY_JECORE", ConditionEnum.NE, "1");
            }
        } else if (condition != null) {
            query.getCustom().remove(condition);
        }
        param.setjQuery(JSON.toJSONString(query));
        Page page = manager.load(param, request);
        return BaseRespResult.successResultPage(page.getRecords(), (long) page.getTotal());
    }

    /**
     * sql语句翻译为中文
     *
     * @param param
     */
    @RequestMapping(value = "/translate", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult translate(BaseMethodArgument param, HttpServletRequest request) {
        String sql = getStringParameter(request, "sql");
        if (StringUtil.isEmpty(sql)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("function.config.translate.empty"));
        }
        DynaBean dynaBean = new DynaBean();
        dynaBean.setStr("sql", sql);
        dynaBean.setStr("funcId", getStringParameter(request, "funcId"));
        String cnSql = funcInfoService.translate(dynaBean);
        return BaseRespResult.successResult(cnSql);
    }

    /**
     * 保存功能配置信息
     *
     * @param param
     */
    @RequestMapping(value = "/doSave", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @Override
    public BaseRespResult doSave(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        String funcId = JEUUID.uuid();
        dynaBean.set("JE_CORE_FUNCINFO_ID", funcId);
        List<DynaBean> listdb = metaService.select(dynaBean.getTableCode(), ConditionsWrapper.builder().eq("FUNCINFO_FUNCCODE", dynaBean.getStr("FUNCINFO_FUNCCODE")));
        if (listdb != null && listdb.size() > 0) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("function.code.repeat"));
        }
        dynaBean.setStr("SY_PATH", "");
        DynaBean db = funcInfoService.doSave(dynaBean);
        developLogService.doDevelopLog("INSERT", "增加", "FUNC", "功能", db.getStr("FUNCINFO_FUNCNAME"), db.getStr("FUNCINFO_FUNCCODE"), db.getStr("JE_CORE_FUNCINFO_ID"),db.getStr("SY_PRODUCT_ID"));
        return BaseRespResult.successResult(db);
    }

    /**
     *获取文件列表
     */
    @RequestMapping(value = "/getFileInfoList", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult getFileInfoList(BaseMethodArgument param, HttpServletRequest request) {
        String[] keys = {"funcRelationId","dataId","funcCode"};
        String redult = StringUtil.checkEmpty(keys,request);
        if(StringUtil.isNotEmpty(redult)){
            return BaseRespResult.errorResult(redult);
        }
        String funcRelationId = getStringParameter(request, "funcRelationId");
        String dataId = getStringParameter(request, "dataId");
        String funcCode = getStringParameter(request, "funcCode");
        JSONTreeNode tree =funcInfoService.getFileInfoList(funcRelationId,dataId,funcCode);
        return tree != null ? BaseRespResult.successResult(DirectJsonResult.buildObjectResult(tree)) : BaseRespResult.successResult(DirectJsonResult.buildObjectResult("{}"));
    }

    /**
     * 保存功能配置信息
     *
     * @param param
     */
    @RequestMapping(value = "/getWorkflowByfuncCode", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult getWorkflowByfuncCode(BaseMethodArgument param, HttpServletRequest request) {
        String code = getStringParameter(request, "funcCode");
        Map<String, String> map = funcInfoService.getWorkflowByfuncCode(code);
        return BaseRespResult.successResult(map);
    }

    /**
     * 更新功能模块信息
     */
    @RequestMapping(value = "/doUpdateModule", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult doUpdateModule(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        List<DynaBean> listdb = metaService.select(dynaBean.getTableCode(),
                ConditionsWrapper.builder()
                        .eq("FUNCINFO_FUNCCODE", dynaBean.getStr("FUNCINFO_FUNCCODE"))
                        .ne("JE_CORE_FUNCINFO_ID", dynaBean.getStr("JE_CORE_FUNCINFO_ID")));
        if (listdb != null && listdb.size() > 0) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("function.code.repeat"));
        }
        DynaBean old = metaService.selectOneByPk("JE_CORE_FUNCINFO", dynaBean.getStr("JE_CORE_FUNCINFO_ID"));
        if (StringUtil.isNotEmpty(dynaBean.getStr("FUNCINFO_PKNAME"))) {
            if (!old.getStr("FUNCINFO_PKNAME").equals(dynaBean.getStr("FUNCINFO_PKNAME"))) {
                return BaseRespResult.errorResult(MessageUtils.getMessage("function.pkName.not.change"));
            }
        }
        metaService.update(dynaBean, ConditionsWrapper.builder().eq("JE_CORE_FUNCINFO_ID", dynaBean.getStr("JE_CORE_FUNCINFO_ID")));
        developLogService.doDevelopLog("UPDATE", "修改", "FUNC", "功能", dynaBean.getStr("FUNCINFO_FUNCNAME"), dynaBean.getStr("FUNCINFO_FUNCCODE"), dynaBean.getStr("JE_CORE_FUNCINFO_ID"),dynaBean.getStr("SY_PRODUCT_ID"));
        return BaseRespResult.successResult(dynaBean);
    }

    /**
     * 功能配置更新处理
     *
     * @param param
     */
    @RequestMapping(value = "/doUpdate", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @Override
    public BaseRespResult doUpdate(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        String JE_CORE_FUNCINFO_ID = dynaBean.getStr("JE_CORE_FUNCINFO_ID");
        if (StringUtil.isEmpty(JE_CORE_FUNCINFO_ID)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("common.params.canotEmpty", "JE_CORE_FUNCINFO_ID"));
        }
        DynaBean old = metaService.selectOneByPk("JE_CORE_FUNCINFO", JE_CORE_FUNCINFO_ID);
        if (StringUtil.isNotEmpty(dynaBean.getStr("FUNCINFO_PKNAME"))) {
            if (!old.getStr("FUNCINFO_PKNAME").equals(dynaBean.getStr("FUNCINFO_PKNAME"))) {
                return BaseRespResult.errorResult(MessageUtils.getMessage("function.pkName.not.change"));
            }
        }
        DynaBean updated = funcInfoService.updateFunInfo(dynaBean);
        developLogService.doDevelopLog("UPDATE", "修改", "FUNC", "功能", updated.getStr("FUNCINFO_FUNCNAME"), updated.getStr("FUNCINFO_FUNCCODE"), updated.getStr("JE_CORE_FUNCINFO_ID"),updated.getStr("SY_PRODUCT_ID"));
        return BaseRespResult.successResult(updated);
    }

    @RequestMapping(value = "/doUpdateHelp", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult doUpdateHelp(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = manager.doUpdate(param, request);
        return BaseRespResult.successResult(dynaBean);

    }


    /**
     * 功能删除，一次只能删除一个功能
     */
    @RequestMapping(value = "/doUpdateFuncCode", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult doUpdateFuncCode(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        if (StringUtil.isEmpty(dynaBean.getStr("JE_CORE_FUNCINFO_ID"))) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("common.params.canotEmpty", "JE_CORE_FUNCINFO_ID"));
        }

        if (StringUtil.isEmpty(dynaBean.getStr("FUNCINFO_FUNCCODE"))) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("common.params.canotEmpty", "FUNCINFO_FUNCCODE"));
        }

        List<DynaBean> listdb = metaService.select("JE_CORE_FUNCINFO",
                ConditionsWrapper.builder()
                        .eq("FUNCINFO_FUNCCODE", dynaBean.getStr("FUNCINFO_FUNCCODE"))
                        .ne("JE_CORE_FUNCINFO_ID", dynaBean.getStr("JE_CORE_FUNCINFO_ID")));
        if (listdb != null && listdb.size() > 0) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("function.code.repeat"));
        }
        funcInfoService.doUpdateFuncCode(dynaBean);
        developLogService.doDevelopLog("UPDATE", "修改", "FUNC", "功能", dynaBean.getStr("FUNCINFO_FUNCNAME"), dynaBean.getStr("FUNCINFO_FUNCCODE"), dynaBean.getStr("JE_CORE_FUNCINFO_ID"),dynaBean.getStr("SY_PRODUCT_ID"));
        return BaseRespResult.successResult(MessageUtils.getMessage("common.delete.success"));
    }

    /**
     * 功能删除，一次只能删除一个功能
     */
    @RequestMapping(value = "/doRemove", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @Override
    public BaseRespResult doRemove(BaseMethodArgument param, HttpServletRequest request) {
        String ids = param.getIds();
        if (Strings.isNullOrEmpty(ids)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("function.id.empty"));
        }
        List<DynaBean> childrens = metaService.select("JE_CORE_FUNCINFO", ConditionsWrapper.builder().apply("SY_PARENT={0}", ids).apply("and  SY_STATUS='1'"));
        if (childrens != null && childrens.size() > 0) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("function.child.not.empty"));
        }

        List<DynaBean> funcInfos = metaService.select("JE_CORE_FUNCINFO", ConditionsWrapper.builder().apply("JE_CORE_FUNCINFO_ID={0}", ids));
        for (DynaBean funcInfo : funcInfos) {
            funcInfoService.removeFuncInfoById(funcInfo.getStr("JE_CORE_FUNCINFO_ID"));
            funcStaticizeCache.removeCache(funcInfo.getStr("FUNCINFO_FUNCCODE"));
            developLogService.doDevelopLog("DELETE", "删除", "FUNC", "功能", funcInfo.getStr("FUNCINFO_FUNCNAME"), funcInfo.getStr("FUNCINFO_FUNCCODE"), funcInfo.getStr("JE_CORE_FUNCINFO_ID"),funcInfo.getStr("SY_PRODUCT_ID"));
        }
        return BaseRespResult.successResult(MessageUtils.getMessage("common.delete.success"));
    }

    /**
     * 数据统计
     */
    @RequestMapping(value = "/doSummary", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public Map<String, Object> doSummary(BaseMethodArgument param, HttpServletRequest request) {
        String tableCode = param.getTableCode();
        String[] types = getStringParameter(request, "types").split(ArrayUtils.SPLIT);
        String[] fields = getStringParameter(request, "fields").split(ArrayUtils.SPLIT);
        Map<String, Object> result = new HashMap<>();
        if (fields == null || fields.length <= 0 || types == null || types.length <= 0 || fields.length != types.length) {
            return result;
        }

        String sql = "select ";
        for (int i = 0; i < fields.length; i++) {
            String type = queryBuilderService.trimBlank(types[i]);
            String field = queryBuilderService.trimBlank(fields[i]);
            sql = sql.concat(type.concat("(").concat(field).concat(") as ").concat(field).concat(","));
        }
        sql = sql.substring(0, sql.length() - 1);
        sql = sql.concat(" from ").concat(tableCode).concat(" where 1 = 1 ");
        String applySql = sql;
        //构建条件
        ConditionsWrapper conditionsWrapper = manager.buildWrapper(param, request);
        //条件sql
        String wrapperSql = conditionsWrapper.getSql();
        if (StringUtils.isNotBlank(wrapperSql)) {
            boolean orderBy = wrapperSql.trim().toLowerCase().startsWith("order by");
            if (orderBy) {
                applySql += wrapperSql;
            } else {
                applySql += " and " + wrapperSql;
            }
        }
        ConditionsWrapper wrapper = ConditionsWrapper.builder(applySql).putAll(conditionsWrapper.getParameter());
        //添加j_query条件
//            queryBuilder.buildWrapper(query,wrapper);
        List<Map<String, Object>> list = this.metaService.selectSql(wrapper);
        if (list != null && list.size() > 0) {
            result = list.get(0);
        }
        return result;
    }

    @RequestMapping(value = "/loadFuncs", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult loadFuncs(BaseMethodArgument param) {
        List<Map<String, Object>> list = metaService.selectSql("SELECT C.*,F.RESOURCEFIELD_XTYPE FROM (SELECT * FROM JE_CORE_RESOURCECOLUMN WHERE RESOURCECOLUMN_FUNCINFO_ID={0}) C LEFT JOIN JE_CORE_RESOURCEFIELD F ON C.RESOURCECOLUMN_PLAN_ID=F.RESOURCEFIELD_PLAN_ID", param.getFuncId());
        return BaseRespResult.successResultPage(list, Long.valueOf(list.size()));
    }

    /**
     * 功能复制
     */
    @RequestMapping(value = "/funcCopy", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult funcCopy(BaseMethodArgument param, HttpServletRequest request) {
        String oldFuncId = getStringParameter(request, "oldFuncId");
        DynaBean dynaBean = new DynaBean("JE_CORE_FUNCINFO", false);
        String newFuncCode = getStringParameter(request, "FUNCINFO_FUNCCODE");
        List<DynaBean> listdb = metaService.select("JE_CORE_FUNCINFO",
                ConditionsWrapper.builder().eq("FUNCINFO_FUNCCODE", newFuncCode));
        if (listdb != null && listdb.size() > 0) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("function.code.repeat"));
        }
        DynaBean oldFuncInfo = metaService.selectOneByPk("JE_CORE_FUNCINFO", oldFuncId);
        if (oldFuncInfo == null) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("function.not.find"));
        }
        if (Strings.isNullOrEmpty(oldFuncInfo.getStr("FUNCINFO_FUNCCODE")) ||
                Strings.isNullOrEmpty(oldFuncInfo.getStr("FUNCINFO_TABLENAME"))
                || Strings.isNullOrEmpty(oldFuncInfo.getStr("FUNCINFO_PKNAME"))) {
            throw new PlatformException("原始功能配置错误！", PlatformExceptionEnum.UNKOWN_ERROR);
        }

        String newFuncName = getStringParameter(request, "FUNCINFO_FUNCNAME");
        String parentId = getStringParameter(request, "SY_PARENT");
        DynaBean newFunc = funcInfoService.copyFunc(newFuncName,newFuncCode,parentId,oldFuncInfo);

        commonService.updateTreePanent4NodeType("JE_CORE_FUNCINFO", newFunc.getStr("SY_PARENT"));
        developLogService.doDevelopLog("COPY", "复制", "FUNC", "功能", dynaBean.getStr("FUNCINFO_FUNCNAME"), dynaBean.getStr("FUNCINFO_FUNCCODE"), dynaBean.getStr("JE_CORE_FUNCINFO_ID"),dynaBean.getStr("SY_PRODUCT_ID"));
        return BaseRespResult.successResult(newFunc);
    }

    /**
     * 通过功能编码得到一条配置信息
     */
    @RequestMapping(value = "/getFuncByCode", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public JSONObject getFuncByCode(HttpServletRequest request) {
        Boolean refresh = Boolean.parseBoolean(getStringParameter(request, "refresh"));
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        String funcCode = dynaBean.getStr("FUNCINFO_FUNCCODE");
        funcInfoService.clearFuncAllStatize(funcCode);
        DynaBean funcBean = metaService.selectOne("JE_CORE_FUNCINFO", ConditionsWrapper.builder()
                .eq("FUNCINFO_FUNCCODE", dynaBean.getStr("FUNCINFO_FUNCCODE")));
        FuncInfo funcInfo = funcInfoService.getFuncInfo(funcCode);
        if (refresh) {
            developLogService.doDevelopLog("UPDATE", "修改", "FUNC", "功能", funcBean.getStr("FUNCINFO_FUNCNAME"), funcBean.getStr("FUNCINFO_FUNCCODE"), funcBean.getStr("JE_CORE_FUNCINFO_ID"),funcBean.getStr("SY_PRODUCT_ID"));
        }
        return DirectJsonResult.buildObjectResult(funcInfo);
    }

    /**
     * 删除缓存
     */
    @RequestMapping(value = "/removeFuncs4cache", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult removeFuncs4cache(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        funcInfoCache.removeCache(dynaBean.getStr("FUNCINFO_FUNCCODE"));
        funcStaticizeCache.removeCache(dynaBean.getStr("FUNCINFO_FUNCCODE"));
        funcConfigCache.removeCache(dynaBean.getStr("FUNCINFO_FUNCCODE"));

        String currentTenantId = SecurityUserHolder.getCurrentAccountTenantId();
        if (!Strings.isNullOrEmpty(currentTenantId)) {
            funcInfoCache.removeCache(currentTenantId, dynaBean.getStr("FUNCINFO_FUNCCODE"));
            funcStaticizeCache.removeCache(currentTenantId, dynaBean.getStr("FUNCINFO_FUNCCODE"));
            funcConfigCache.removeCache(currentTenantId, dynaBean.getStr("FUNCINFO_FUNCCODE"));
        }

        return BaseRespResult.successResult(null, "缓存已清理");
    }

    /**
     * 粘贴正向软连接
     */
    /*@RequestMapping(value = "/copySoftFun", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult copySoftFun(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        String oldFuncId = getStringParameter(request, "oldFuncId");
        String createNew = getStringParameter(request, "createNew");
        DynaBean oldFunInfo = metaService.selectOneByPk("JE_CORE_FUNCINFO", oldFuncId);
        if (oldFuncId == null) {
            return BaseRespResult.errorResult("目标功能未找到!");
        }
        if (Strings.isNullOrEmpty(oldFunInfo.getStr("FUNCINFO_FUNCCODE")) || Strings.isNullOrEmpty(oldFunInfo.getStr("FUNCINFO_TABLENAME"))
                || Strings.isNullOrEmpty(oldFunInfo.getStr("FUNCINFO_PKNAME"))) {
            return BaseRespResult.errorResult("原功能信息不全，不能复制!");
        }

        String funcId = JEUUID.uuid();
        dynaBean.set("JE_CORE_FUNCINFO_ID", funcId);
        dynaBean.set("SY_PATH", dynaBean.getStr("SY_PATH") + "/" + funcId);
        if ("FUNC".equals(dynaBean.getStr("FUNCINFO_NODEINFOTYPE")) || "FUNCFIELD".equals(dynaBean.getStr("FUNCINFO_NODEINFOTYPE"))) {
            funcInfoService.buildDefaultFuncInfo(dynaBean);
        }
        commonService.buildModelCreateInfo(dynaBean);
        metaService.insert(dynaBean);
        DynaBean newFunInfo = dynaBean;
        newFunInfo = funcInfoService.copySoftFuncInfo(newFunInfo, oldFunInfo);
        commonService.updateTreePanent4NodeType("JE_CORE_FUNCINFO", newFunInfo.getStr("SY_PARENT"));
        return BaseRespResult.successResult(newFunInfo);
    }*/

    /**
     * 只读硬连接(只加入子功能列表中)
     */
    @RequestMapping(value = "/copyHard", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult copyHard(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        String oldFuncId = getStringParameter(request, "oldFuncId");
        DynaBean mainFunInfo = metaService.selectOneByPk("JE_CORE_FUNCINFO", dynaBean.getStr("JE_CORE_FUNCINFO_ID"));
        if (mainFunInfo == null) {
            return BaseRespResult.errorResult("目标的主功能未找到!");
        }
        DynaBean oldFunInfo = metaService.selectOneByPk("JE_CORE_FUNCINFO", oldFuncId);
        if (oldFunInfo == null) {
            return BaseRespResult.errorResult("本功能未找到!");
        }
        DynaBean funRelation = new DynaBean("JE_CORE_FUNCRELATION", false);
        funRelation.set(BeanService.KEY_PK_CODE, "JE_CORE_FUNCRELATION_ID");
        funRelation.set("FUNCRELATION_FUNCINFO_ID", mainFunInfo.getStr("JE_CORE_FUNCINFO_ID"));
        funRelation.set("SY_STATUS", Enable.TRUE);
        funRelation.set("SY_CREATETIME", DateUtils.formatDate(new Date()));
        funRelation.set("FUNCRELATION_CODE", oldFunInfo.get("FUNCINFO_FUNCCODE"));
        funRelation.set("FUNCRELATION_NAME", oldFunInfo.get("FUNCINFO_FUNCNAME"));
        funRelation.set("FUNCRELATION_ENTITYNAME", oldFunInfo.get("FUNCINFO_ENTITYNAME"));
        funRelation.set("FUNCRELATION_TABLENAME", oldFunInfo.get("FUNCINFO_TABLENAME"));
        //取得当前功能的sysmode  CP、CPKZ或XMKF
        String sysMode = mainFunInfo.getStr("FUNCINFO_SYSMODE");
        funRelation.set("FUNCRELATION_SYSMODE", sysMode);
        funRelation.set("FUNCRELATION_RELYONTYPE", FunCopyType.ZDYLJ);
        metaService.insert(funRelation);
        //建立复制目标的依赖
        return BaseRespResult.successResult(null, "执行成功!");
    }

    /**
     * 通过code获得功能单表信息
     *
     * @author marico
     * @date 2012-3-27 下午04:42:54
     */
    @RequestMapping(value = "/getInfoByCode", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult getInfoByCode(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        DynaBean funInfo = metaService.selectOne("JE_CORE_FUNCINFO", ConditionsWrapper.builder()
                .apply("FUNCINFO_FUNCCODE={0} AND FUNCINFO_NODEINFOTYPE IN ('FUNC','FUNCFIELD')", dynaBean.getStr("FUNCINFO_FUNCCODE")));
        if (funInfo == null) {
            return BaseRespResult.errorResult("无此功能!");
        }
        return BaseRespResult.successResult(funInfo);
    }

    /**
     * 清空功能
     */
    @RequestMapping(value = "/clearFuncInfo", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult clearFuncInfo(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = new DynaBean();
        String funcinfoId = getStringParameter(request, "JE_CORE_FUNCINFO_ID");
        if (Strings.isNullOrEmpty(funcinfoId)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("function.id.empty"));
        }
        dynaBean.setStr("JE_CORE_FUNCINFO_ID", funcinfoId);
        funcInfoService.clearFuncInfo(dynaBean);
        return BaseRespResult.successResult(null, MessageUtils.getMessage("common.clear.success"));
    }

    /**
     * 解除功能软链接关系
     */
    @RequestMapping(value = "/removeFunRelyon", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult removeFunRelyon(BaseMethodArgument param, HttpServletRequest request) {
        String ids = getStringParameter(request, "ids");
        if (Strings.isNullOrEmpty(ids)) {
            return BaseRespResult.errorResult("传入主键失败!");
        }
        funcInfoService.removeFuncRelyon(ids);
        return BaseRespResult.successResult(null, "解除关系成功!");
    }

    /**
     * 功能回值
     *
     * @author linzhichao
     */
    @RequestMapping(value = "/returnInfo", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult returnInfo(BaseMethodArgument param, HttpServletRequest request) {
        String updateSql = getStringParameter(request, "updateSql");
        String selectSql = getStringParameter(request, "selectSql");
        String fields = getStringParameter(request, "fields");
        JSONObject obj = new JSONObject();
        obj.put("success", false);
        //更新信息
        // TODO 禁止前端传sql
//        int count = metaService.executeSql(updateSql);
        int count = 0;
        if (count > 0) {
            obj.put("success", true);
            JSONObject jb = new JSONObject();
            //查询信息
            if (!StringUtils.isEmpty(selectSql)) {
                List list = metaService.selectSql(selectSql);
                String[] fs = fields.split(ArrayUtils.SPLIT);
                for (int i = 0; i < fs.length; i++) {
                    jb.put(fs[i], list.get(i));
                }
            }
            obj.put("obj", jb);
        }
        return BaseRespResult.successResult(obj.toString());
    }

    /**
     * 求和
     *
     * @author linzhichao
     */
    @RequestMapping(value = "/summary", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult summary(BaseMethodArgument param, HttpServletRequest request) {
        String tableCode = getStringParameter(request, "tableCode");
        String whereSql = getStringParameter(request, "whereSql");
        String type = getStringParameter(request, "type");
        String field = getStringParameter(request, "field");
        String sql = "select ".concat(type).concat("(").concat(field).concat(") from ").concat(tableCode).concat(" where 1=1 ").concat(whereSql);
        List<Map<String, Object>> list = metaService.selectSql(sql);
        return BaseRespResult.successResult(list.get(0) == null ? "" : list.get(0).toString());
    }

    @RequestMapping(value = "/loadFunc", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult loadFunc(BaseMethodArgument param, HttpServletRequest request) {
        Page page = manager.load(param, request);
        return BaseRespResult.successResultPage(page.getRecords(), (long) page.getTotal());
    }

    /**
     * 根据主键获取业务数据
     */
    @RequestMapping(value = "/getInformationById", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult getInformationById(BaseMethodArgument param, HttpServletRequest request) {
        String pkValue = param.getPkValue();
        String code = param.getFuncCode();
        String configType = getStringParameter(request, "type");
        if (StringUtil.isEmpty(pkValue)) {
            pkValue = getStringParameter(request, "pkValue");
        }
        Map<String, Object> map = funcInfoService.getInformationById(pkValue, code, configType);
        return BaseRespResult.successResult(map);
    }


    /**
     * 根据主键获取业务数据
     */
    @Deprecated
    @Override
    @RequestMapping(value = "/getInfoById", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult getInfoById(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        String pkValue = param.getPkValue();
        String queryColumns = param.getQueryColumns();
        if (StringUtil.isEmpty(pkValue)) {
            pkValue = dynaBean.getPkValue();
        }
        DynaBean selectOne = null;
        if (StringUtil.isNotEmpty(queryColumns)) {
            selectOne = metaService.selectOneByPk("JE_CORE_FUNCINFO", pkValue, queryColumns);
        } else {
            selectOne = metaService.selectOneByPk("JE_CORE_FUNCINFO", pkValue);
        }
        if (selectOne == null) {
            return BaseRespResult.successResult(new HashMap<>());
        }
        return BaseRespResult.successResult(selectOne.getValues());
    }

    /**
     * 功能字段配置同步
     */
    @RequestMapping(value = "/syncConfig", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult syncConfig(HttpServletRequest request) {
        DynaBean dynaBean = new DynaBean();
        dynaBean.setStr("toFuncCode", getStringParameter(request, "toFuncCode"));
        dynaBean.setStr("formFuncCode", getStringParameter(request, "formFuncCode"));
        dynaBean.setStr("columnCodes", getStringParameter(request, "columnCodes"));
        dynaBean.setStr("type", getStringParameter(request, "type"));

        String[] key = {"toFuncCode", "formFuncCode", "type"};
        String result = StringUtil.checkEmpty(key, request);
        if (StringUtil.isNotEmpty(result)) {
            return BaseRespResult.errorResult(result);
        }
        funcInfoService.syncConfig(dynaBean);
        return BaseRespResult.successResult(MessageUtils.getMessage("common.operation.success"));
    }


    @RequestMapping(value = "/cleanFiledOtherConfig", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult cleanFiledOtherConfig(HttpServletRequest request) {
        List<DynaBean> list = metaService.select("JE_CORE_RESOURCEFIELD",
                ConditionsWrapper.builder().eq("RESOURCEFIELD_XTYPE","vueuserfield")
                        .like("RESOURCEFIELD_OTHERCONFIG","deptQuery"));
        for(DynaBean dynaBean:list){
            try{
                String config = dynaBean.getStr("RESOURCEFIELD_OTHERCONFIG");
                if(StringUtil.isNotEmpty(config)){
                    JSONObject jsonObject =JSON.parseObject(config);
                    if(jsonObject.containsKey("deptQuery")){
                        jsonObject.put("deptQuery","");
                    }
                    if(jsonObject.containsKey("roleQuery")){
                        jsonObject.put("roleQuery","");
                    }

                    if(jsonObject.containsKey("organQuery")){
                        jsonObject.put("organQuery","");
                    }
                    dynaBean.setStr("RESOURCEFIELD_OTHERCONFIG",jsonObject.toString());
                    metaService.update(dynaBean);
                }
            }catch (Exception e){
            }

        }
        return BaseRespResult.successResult("");

    }

}
